/**
 * Copyright (C) 2011 Moss Computing <support@mosscomputing.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.oslef.csv;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public final class RowWriter {

	private List<String> columns = new ArrayList<String>();
	private Map<String, String> values = new HashMap<String, String>();
	private CSVWriter writer;
	
	public RowWriter(List<String> columns, File file) throws IOException {
		this.columns.addAll(columns);
		this.writer = new CSVWriter(file);
	}
	
	public RowWriter(List<String> columns, CSVWriter writer) {
		this.columns.addAll(columns);
		this.writer = writer;
	}
	
	public void put(String key, String value) {
		values.put(key, value);
	}
	
	public void writeHeader() throws IOException {
		for (String c : columns) {
			writer.write(c);
		}
		writer.newLine();
	}
	
	public void write() throws IOException {
		for (String c : columns) {
			String v = values.get(c);
			if (v != null) writer.write(values.get(c));
			else writer.write("");
		}
		writer.newLine();
	}
	
	public void clear() {
		values.clear();
	}
	
	public void close() throws IOException {
		writer.close();
	}
}
